package com.zeei.ems.meet.hik;

import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.Client;
import com.hikvision.artemis.sdk.Request;
import com.hikvision.artemis.sdk.Response;
import com.hikvision.artemis.sdk.constant.Constants;
import com.hikvision.artemis.sdk.constant.ContentType;
import com.hikvision.artemis.sdk.constant.HttpHeader;
import com.hikvision.artemis.sdk.constant.MsgConstants;
import com.hikvision.artemis.sdk.enums.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CustomArtemisHttpUtil extends ArtemisHttpUtil {

    //自定义参与签名Header前缀（可选,默认只有"X-Ca-"开头的参与到Header签名）
    //private final static List<String> CUSTOM_HEADERS_TO_SIGN_PREFIX = new ArrayList<String>();

    //调用网关成功的标志,标志位
    private final static String SUCC_PRE = "2";

    //调用网关重定向的标志,标志位
    private final static String REDIRECT_PRE = "3";

    /**
     * postString请求
     *
     * @param path        artemis配置的get请求的路径 是一个数组长度为1的Hashmap集合，只存一组数据，key为http的请求方式，value为getHost()后面的path路径。
     * @param body        postString String请求体
     * @param querys      map类型  post请求的url查询参数（url中的query参数,没有就是为空）形如 "?aa=1&&bb=2"形式参数变成map键值对 query.put("aa","1");query.put("bb","2")
     * @param accept      指定客户端能够接收的内容类型，该参数传空时的默认全部类型接受
     * @param contentType 请求的与实体对应的MIME信息，该参数传空时的取默认值("application/text; charset=UTF-8")
     * @return  POST json类型接口  返回字符串类型
     */
    public static String doPostStringArtemis(Map<String, String> path, String body,
                                             Map<String, String> querys, String accept, String contentType, HikConfig artemisConfig) {
        /**
         * 根据传入的path获取是请求是http还是https
         */
        String httpSchema = (String) path.keySet().toArray()[0];

        if (httpSchema == null || StringUtils.isEmpty(httpSchema))
            throw new RuntimeException(MsgConstants.HTTP_SCHEMA_ERROR + "httpSchema: " + httpSchema);
        String responseStr = null;
        try {

            Map<String, String> headers = new HashMap<String, String>();
            //（必填）根据期望的Response内容类型设置
            if (StringUtils.isNotBlank(accept)) {
                headers.put(HttpHeader.HTTP_HEADER_ACCEPT, accept);
            } else {
                headers.put(HttpHeader.HTTP_HEADER_ACCEPT, "*/*");
            }
            //（POST/PUT请求必选）请求Body内容格式请求的与实体对应的MIME信息
            if (StringUtils.isNotBlank(contentType)) {
                headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, contentType);
            } else {
                headers.put(HttpHeader.HTTP_HEADER_CONTENT_TYPE, ContentType.CONTENT_TYPE_TEXT);
            }
            Request request = new Request(Method.POST_STRING, httpSchema + artemisConfig.getHost(),
                    path.get(httpSchema), artemisConfig.getAppKey(), artemisConfig.getAppSecret(), Constants.DEFAULT_TIMEOUT);
            request.setHeaders(headers);
            //请求的query
            request.setQuerys(querys);
            //请求的bodyString
            request.setStringBody(body);
            //调用服务端
            Response response = Client.execute(request);

            responseStr = getResponseResult(response);

        } catch (Exception e) {
            log.error("the Artemis PostString Request is failed[doPostStringArtemis]", e);
        }
        return responseStr;
    }

    /**
     * response 获取body内容
     *
     * @param response
     */
    private static String getResponseResult(Response response) {
        String responseStr = null;

        int statusCode = response.getStatusCode();

        if (String.valueOf(statusCode).startsWith(SUCC_PRE) || String.valueOf(statusCode).startsWith(REDIRECT_PRE)) {//调用Artemis网关成功
            responseStr = response.getBody();
            log.info("the Artemis Request is Success,statusCode:" + statusCode + " SuccessMsg:" + response.getBody());

        } else {
            String msg = response.getErrorMessage();
            responseStr = response.getBody();
            log.error("the Artemis Request is Failed,statusCode:" + statusCode + " errorMsg:" + msg);
        }
        return responseStr;
    }
}
